

package cn.hsa.fqz.task.service.impl;

import cn.hsa.fqz.common.enums.IncidentsResultEnum;
import cn.hsa.fqz.common.enums.ProcessStatusEnum;
import cn.hsa.fqz.common.utils.snowflake.IdUtil;
import cn.hsa.fqz.task.controller.vo.TaskRoleAuthVO;
import cn.hsa.fqz.task.dao.*;
import cn.hsa.fqz.task.entity.*;
import cn.hsa.fqz.task.enums.TaskSourceEnums;
import cn.hsa.fqz.task.enums.UserCategoryEnums;
import cn.hsa.fqz.task.service.IDataFluxService;
import cn.hsa.fqz.task.service.RegionService;
import cn.hsa.fqz.task.service.TTaskService;
import cn.hsa.fqz.task.service.TUserMappingService;
import cn.hsa.fqz.task.service.dto.*;
import cn.hsa.fqz.util.UserRegionUtils;
import cn.hsa.hsaf.core.framework.util.PageResult;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class TTaskServiceImpl implements TTaskService {

    @Autowired
    private TTaskClueSubjectMapper tTaskClueSubjectMapper;
    @Autowired
    private TTaskSqlExecuteMapper tTaskSqlExecuteMapper;
    @Autowired
    private TTaskProcessMapper tTaskProcessMapper;
    @Autowired
    private TTaskClueRtMapper tTaskClueRtMapper;
    @Autowired
    private TTaskMapper tTaskMapper;

    @Autowired
    private RegionService regionService;

    @Autowired
    IDataFluxService dataFluxService;

    @Autowired
    private TTaskConfigMapper tTaskConfigMapper;
    @Autowired
    private TTaskAssignMapper tTaskAssignMapper;
    @Autowired
    private TTaskRoleAuthMapper tTaskRoleAuthMapper;

    @Autowired
    private TUserMappingService userMappingService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addTask(LoginUserDTO user, Integer csId) {

        TTaskClueSubject subject = tTaskClueSubjectMapper.selectByPrimaryKey(csId);
        if (subject == null) {
            return WrapperResponse.error(-1,"任务发布失败，线索不存在！",null);
        }

        TTaskClueRt tTaskClueRt = tTaskClueRtMapper.selectByCsId(csId);
        if (tTaskClueRt != null) {
            return WrapperResponse.error(-1,"任务发布失败，已经存在对应采集任务！",null);
        }
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(user.getRegion());
        TTask tTask = new TTask();
        //标题
        tTask.setTitle(subject.getCsTitle());
        //任务发布人
        tTask.setCreateBy(user.getUid());
        //发布时间
        tTask.setCreateTime(new Date());
        //处理过程
        tTask.setResult(IncidentsResultEnum.CREATE.name());
        //来源
        tTask.setSource(subject.getCsSources());
        //主体
        tTask.setSubject(subject.getCsSubject());
        //任务编码
        tTask.setTaskCode(IdUtil.INSTANCE.get());
        //0:子级任务 1：父级任务
        tTask.setIsParent(1);
        //签收状态
        tTask.setSignStatus(0);

        tTask.setPrv(user.getRegion());
        tTask.setBelongTo(enums.toString());
        tTask.setDesc(TaskSourceEnums.DIRECT.name());
        tTask.setSupplierStatus(0);
        boolean condition = tTaskMapper.insert(tTask) > 0;

        //保存线索对应任务关系
        TTaskClueRt rt = new TTaskClueRt();
        rt.setClueId(csId);
        rt.setTaskId(tTask.getId());
        tTaskClueRtMapper.insert(rt);

        return WrapperResponse.success(condition);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addSubTask(LoginUserDTO user, Integer pTaskId, String... orgIds) {

        TTask parentTask = tTaskMapper.selectByPrimaryKey(pTaskId);
        List<String> prvs = tTaskMapper.selectPrvsByPid(pTaskId);
        List<String> orgLs = Arrays.asList(orgIds);
        Collection<String> orgCollection = CollectionUtils.subtract(orgLs, prvs);
        log.info("当前taskId: " + pTaskId);
        if(CollectionUtil.isEmpty(orgCollection)){
            return WrapperResponse.error(-1,"当前任务无对应的子任务需要拆分！",null);
        }
        if (Objects.isNull(parentTask)) {
            return WrapperResponse.error(-1,"任务发布失败，主任务不存在！",null);
        }
        if (parentTask.getIsParent() != 1) {
            return WrapperResponse.error(-1,"当前任务为子任务无法再次分发！",null);
        }
        if (!IncidentsResultEnum.PROCESSED.name().equals(parentTask.getResult())) {
            return WrapperResponse.error(-1,"当前任务状态，不可发布子任务！",null);
        }
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(user.getRegion());
        List<TTask> tmpList = Lists.newArrayList();
        for (String orgId : orgCollection) {
            if(enums == UserCategoryEnums.PROVINCE){
                pTaskId = parentTask.getPid();
            }
            TTaskClueRt clueRt = tTaskClueRtMapper.selectByTaskId(pTaskId);

            String regName = "";
            LambdaQueryWrapper<RegionDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RegionDO::getRegion,orgId);
            RegionDO regionDO =  regionService.getOne(wrapper);
            if(Objects.nonNull(regionDO)){
                if(enums == UserCategoryEnums.PROVINCE){
                    regName = regionDO.getCity();
                }else{
                    regName = regionDO.getProvice();
                }
            }
            int vb = tTaskMapper.isExistSubTask(pTaskId, orgId,enums.toString());
            if (vb > 0) {
                return WrapperResponse.error(-1,"任务id：【"+pTaskId+"】在行政区划【"+orgId+"】中已有子任务，无法再次发布！",null);
            }
            TTask tTask = new TTask();
            //标题
            tTask.setTitle(parentTask.getTitle() + "-子任务-" + regName);
            //任务发布人
            tTask.setCreateBy(user.getUid());
            //发布时间
            tTask.setCreateTime(new Date());
            //处理过程
            tTask.setResult(IncidentsResultEnum.PROCESSED.name());
            //来源
            tTask.setSource(parentTask.getSource());
            //主体
            tTask.setSubject(parentTask.getSubject());
            //任务编码
            tTask.setTaskCode(parentTask.getTaskCode());
            //0:子级任务 1：父级任务
            tTask.setIsParent(0);
            //父级id
            if(enums == UserCategoryEnums.PROVINCE){
                tTask.setPid(parentTask.getId());
            }else{
                tTask.setPid(pTaskId);
            }
            //签收状态
            tTask.setSignStatus(0);
            //指定行政区划接收子任务
            tTask.setReceiveBy(orgId);
            //行政区划名称
            tTask.setReceiveRegName(regName);
            tTask.setPrv(orgId);
            tTask.setSupplierStatus(1);
            tTask.setBelongTo(enums.toString());

            tTaskMapper.insert(tTask);
            tmpList.add(tTask);

            //保存线索对应任务关系
            TTaskClueRt rt = new TTaskClueRt();
            rt.setClueId(clueRt.getClueId());
            rt.setTaskId(tTask.getId());
            tTaskClueRtMapper.insert(rt);

            //记录分发流程-登记
            insertTaskProcess(user.getRegion(), tTask, ProcessStatusEnum.CREATE);

            //记录分发流程-采集
            insertTaskProcess(user.getRegion(), tTask, ProcessStatusEnum.PROCESSED);
        }
        log.info("插入的任务数量: "+tmpList.size());
        return WrapperResponse.success(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addDistribute(LoginUserDTO loginUser, Integer id, String region) {

        TTask tTask = tTaskMapper.selectByPrimaryKey(id);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务分发失败，任务不存在！",null);
        }
        if (!IncidentsResultEnum.PROCESSED.name().equals(tTask.getResult())) {
            IncidentsResultEnum incidentsResultEnum = IncidentsResultEnum.get(tTask.getResult());
            return WrapperResponse.error(-1,"当前任务状态为'" + (incidentsResultEnum == null ? "" : incidentsResultEnum.getLabel()) + "'不可分发！",null);
        }
        //下发人
        tTask.setSendBy(loginUser.getRegion());
        //下发时间
        tTask.setSendTime(new Date());
        //处理过程
        tTask.setResult(IncidentsResultEnum.DISTRIBUTE.name());
        tTask.setReceiveBy(region);
        TTaskAssign assign = new TTaskAssign();
        assign.setPTaskId(tTask.getPid());
        assign.setTaskId(tTask.getId());
        assign.setRegion(region);
        tTaskAssignMapper.insert(assign);

        //记录分发流程-分发
        insertTaskProcess(loginUser.getRegion(),tTask,ProcessStatusEnum.DISTRIBUTE);
        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WrapperResponse<Boolean> addDistributeAll(LoginUserDTO loginUser, Integer pTaskId){
        List<TTask> subTaskList = tTaskMapper.selectByTaskPid(pTaskId);
        if(subTaskList.stream().anyMatch(ta -> (ta.getResult().equals(IncidentsResultEnum.DISTRIBUTE.name())||ta.getResult().equals(IncidentsResultEnum.SIGNATURE.name())))){
            return WrapperResponse.error(-1,"当前子任务列表存在已分发的子任务，不可一键分发！",null);
        }
        if(CollectionUtil.isNotEmpty(subTaskList)){
            for (TTask tTask:subTaskList) {
                //下发人
                tTask.setSendBy(loginUser.getRegion());
                //下发时间
                tTask.setSendTime(new Date());
                //处理过程
                tTask.setResult(IncidentsResultEnum.DISTRIBUTE.name());

                TTaskAssign assign = new TTaskAssign();
                assign.setPTaskId(tTask.getPid());
                assign.setTaskId(tTask.getId());
                assign.setRegion(tTask.getPrv());
                tTaskAssignMapper.insert(assign);
                tTaskMapper.updateByPrimaryKeySelective(tTask);
                //记录分发流程-分发
                insertTaskProcess(loginUser.getRegion(),tTask,ProcessStatusEnum.DISTRIBUTE);
            }
            return WrapperResponse.success(true);
        }
        return WrapperResponse.success(false);
    }

    @Override
    public WrapperResponse<Boolean> addRollback(LoginUserDTO loginUser, Integer taskId) {
        TTask tTask = tTaskMapper.selectByPrimaryKey(taskId);
        if(tTask.getResult().equals(ProcessStatusEnum.SIGNATURE) || tTask.getResult().equals(ProcessStatusEnum.FINISHED)){
            return WrapperResponse.error(-1, "当前任务是签收或者办结状态，不能回退",null);
        }else{
            TTaskAssign tTaskAssign = tTaskAssignMapper.selectByTaskId(taskId);
            tTaskAssignMapper.deleteByPrimaryKey(tTaskAssign.getId());
            //下发时间
            tTask.setSendTime(null);
            tTask.setSendBy(null);
            //处理过程
            tTask.setResult(IncidentsResultEnum.PROCESSED.name());
            insertTaskProcess(loginUser.getRegion(), tTask, ProcessStatusEnum.BACK);
            return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
        }
    }

    @Override
    public WrapperResponse<Boolean> addSupplier(Integer taskId, Integer supplierStatus) {
        tTaskMapper.supplier(taskId,supplierStatus);
        return WrapperResponse.success(true);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addFinish(LoginUserDTO loginUser, Integer taskId) {
        String region = loginUser.getRegion();
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(region);

        TTask tTask = tTaskMapper.selectByPrimaryKey(taskId);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务分发失败，任务不存在！",null);
        }
        if(enums == UserCategoryEnums.GLOBAL){
            List<TTask> taskList = tTaskMapper.selectByTaskCode(tTask.getTaskCode());
            taskList.remove(tTask); //把自己去掉，以便于下面统一处理
            List<TTask> removeList = taskList.stream().filter( e -> e.getResult().equals(IncidentsResultEnum.FINISHED.name())).collect(Collectors.toList());
            //删除已经办结的任务
            taskList.removeAll(removeList);
            if(CollectionUtil.isNotEmpty(taskList)){
                taskList.forEach( e -> {
                    //记录分发流程-分发
                    insertTaskProcess(region, e,ProcessStatusEnum.FINISHED);
                });
            }
            tTaskMapper.finishTask(tTask.getTaskCode());
        }else if(enums == UserCategoryEnums.PROVINCE){
            List<TTask> taskList = tTaskMapper.selectByTaskPid(tTask.getId());
            List<TTask> removeList = taskList.stream().filter( e -> e.getResult().equals(IncidentsResultEnum.FINISHED.name())).collect(Collectors.toList());
            //删除已经办结的任务
            taskList.removeAll(removeList);
            if(CollectionUtil.isNotEmpty(taskList)){
                taskList.forEach( e -> {
                    //记录分发流程-分发
                    insertTaskProcess(region, e,ProcessStatusEnum.FINISHED);
                });
            }
            tTaskMapper.finishSubTask(tTask.getId());
        }
        //下发人
        tTask.setSendBy(loginUser.getUid());
        //下发时间
        tTask.setSendTime(new Date());
        //处理过程
        tTask.setResult(IncidentsResultEnum.FINISHED.name());
        insertTaskProcess(region, tTask,ProcessStatusEnum.FINISHED);

        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }

    public Integer insertTaskProcess(String region,TTask tTask,ProcessStatusEnum processStatusEnum){
        TTaskProcess process = new TTaskProcess();
        process.setTitle(tTask.getTitle());
        process.setFrom(region);
        process.setTo(tTask.getReceiveBy());
        process.setTaskId(tTask.getId());
        process.setMemo(processStatusEnum.getLabel());
        process.setOccurDate(new Date());
        process.setOperation(processStatusEnum.getLabel());
        return tTaskProcessMapper.insert(process);
    }

    @Override
    public WrapperResponse<Boolean> addSupplierFinish(LoginUserDTO loginUser, Integer taskId) {
        TTask tTask = tTaskMapper.selectByPrimaryKey(taskId);
        if(tTask.getResult().equals(IncidentsResultEnum.FINISHED.name())){
            return WrapperResponse.fail("当前任务已经办结，无需再次确认",null);
        }
        //下发人
        tTask.setSendBy(loginUser.getUid());
        //下发时间
        tTask.setSendTime(new Date());
        //处理过程
        tTask.setResult(IncidentsResultEnum.FINISHED.name());
        insertTaskProcess(loginUser.getRegion(), tTask,ProcessStatusEnum.FINISHED);
        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addBack(LoginUserDTO loginUser, Integer id) {

        if (true) {
            return WrapperResponse.error(-1,"接口停用！",null);
        }

        TTask tTask = tTaskMapper.selectByPrimaryKey(id);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务取回失败，任务不存在！",null);
        }

        if (!IncidentsResultEnum.DISTRIBUTE.name().equals(tTask.getResult())) {
            IncidentsResultEnum incidentsResultEnum = IncidentsResultEnum.get(tTask.getResult());
            return WrapperResponse.error(-1,"任务状态为'" + (incidentsResultEnum == null ? "" : incidentsResultEnum.getLabel()) + "'，不能发起取回请求！",null);
        }

        tTask.setBackOptUser(loginUser.getUid());
        tTask.setBackTime(new Date());
        tTask.setResult(IncidentsResultEnum.BACK.name());

        //记录分发流程-取回
        TTaskProcess process = new TTaskProcess();
        process.setTitle(tTask.getTitle());
        process.setFrom(tTask.getReceiveBy());
        process.setTo(loginUser.getRegion());
        process.setTaskId(tTask.getId());
        process.setMemo(ProcessStatusEnum.BACK.getLabel());
        process.setOccurDate(new Date());
        process.setOperation(ProcessStatusEnum.BACK.getLabel());

        tTaskProcessMapper.insert(process);

        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }

    @Override
    public WrapperResponse<Integer> addSendTo(LoginUserDTO loginUser,Integer id){
        String region = loginUser.getRegion();
         UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(region);
         if(region.substring(2,4).endsWith("99")){
             return WrapperResponse.error(-1,"省本级用户不能移交省级任务！",null);
         }
        TTask tTask = tTaskMapper.selectByPrimaryKey(id);
        String isSendTo = tTaskMapper.isExsitsSendTo(id);
        if(StringUtils.isNotEmpty(isSendTo)){
            return WrapperResponse.error(-1,"当前任务已移交，不能再次移交！",null);
        }
        Integer result = 0;
        if(enums == UserCategoryEnums.PROVINCE ){
            TTask newTask = new TTask();
            BeanUtils.copyProperties(tTask,newTask);
            newTask.setIsParent(1);
            //任务发布人
            newTask.setCreateBy(loginUser.getUid());
            //发布时间
            newTask.setCreateTime(new Date());
            //处理过程
            newTask.setResult(IncidentsResultEnum.PROCESSED.name());
            //签收状态
            newTask.setSignStatus(0);
            newTask.setPrv(region);
            newTask.setBelongTo(enums.toString());
            newTask.setId(null);
            newTask.setDesc(TaskSourceEnums.ASSIGNED.name());
            newTask.setSupplierStatus(1);
            tTaskMapper.insert(newTask);

            TTaskClueRt trt = tTaskClueRtMapper.selectByTaskId(newTask.getPid());

            //保存线索对应任务关系
            TTaskClueRt rt = new TTaskClueRt();
            rt.setClueId(trt.getClueId());
            rt.setTaskId(newTask.getId());
            tTaskClueRtMapper.insert(rt);

            //记录分发流程-登记
            TTaskProcess process1 = new TTaskProcess();
            process1.setTitle(newTask.getTitle());
            process1.setFrom(region);
            process1.setTo(region);
            process1.setTaskId(tTask.getId());
            process1.setMemo(ProcessStatusEnum.PROCESSED.getLabel());
            process1.setOccurDate(new Date());
            process1.setOperation(ProcessStatusEnum.PROCESSED.getLabel());
            result = tTaskProcessMapper.insert(process1);
            tTaskMapper.setIsOverDue(id);
        }
        return WrapperResponse.success(result);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WrapperResponse<Boolean> addReceive(LoginUserDTO loginUser, Integer id,Integer needSplit) {
        String region = loginUser.getRegion();

        TTask tTask = tTaskMapper.selectByPrimaryKey(id);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务接收失败，任务不存在！",null);
        }

        String regName = "";
        LambdaQueryWrapper<RegionDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegionDO::getRegion,region);
        RegionDO regionDO =  regionService.getOne(wrapper);
        if(Objects.nonNull(regionDO)){
            regName = regionDO.getProvice();
        }
        tTask.setReceiveUser(region);
        tTask.setReceiveRegName(regName);
        tTask.setReceiveTime(new Date());
        tTask.setSignStatus(1);
        tTask.setResult(IncidentsResultEnum.SIGNATURE.name());

        //记录分发流程-签收
        TTaskProcess process = new TTaskProcess();
        process.setTitle(tTask.getTitle());
        process.setFrom(tTask.getSendBy());
        process.setTo(loginUser.getRegion());
        process.setTaskId(tTask.getId());
        process.setMemo(ProcessStatusEnum.SIGNATURE.getLabel());
        process.setOccurDate(new Date());
        process.setOperation(ProcessStatusEnum.SIGNATURE.getLabel());

        tTaskProcessMapper.insert(process);

        boolean condition = tTaskMapper.updateByPrimaryKeySelective(tTask) > 0;

        // TODO 签收需要根据当前用户所属来判断，如果是省级用户签收，需要再生成一条PROVICE类型的父级任务，如果是市级签收，则不用追加
        /*UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(region);
        if(enums == UserCategoryEnums.PROVINCE && needSplit.intValue() == 1){
            TTask newTask = new TTask();
            BeanUtils.copyProperties(tTask,newTask);
            newTask.setIsParent(1);
            //任务发布人
            newTask.setCreateBy(loginUser.getUid());
            //发布时间
            newTask.setCreateTime(new Date());
            //处理过程
            newTask.setResult(IncidentsResultEnum.PROCESSED.name());
            //签收状态
            newTask.setSignStatus(0);
            newTask.setPrv(region);
            newTask.setBelongTo(enums.toString());
            newTask.setId(null);
            newTask.setDesc(TaskSourceEnums.ASSIGNED.name());
            tTaskMapper.insert(newTask);

            TTaskClueRt trt = tTaskClueRtMapper.selectByTaskId(newTask.getPid());

            //保存线索对应任务关系
            TTaskClueRt rt = new TTaskClueRt();
            rt.setClueId(trt.getClueId());
            rt.setTaskId(newTask.getId());
            tTaskClueRtMapper.insert(rt);

            //记录分发流程-登记
            TTaskProcess process1 = new TTaskProcess();
            process1.setTitle(newTask.getTitle());
            process1.setFrom("000000");
            process1.setTo(region);
            process1.setTaskId(tTask.getId());
            process1.setMemo(ProcessStatusEnum.PROCESSED.getLabel());
            process1.setOccurDate(new Date());
            process1.setOperation(ProcessStatusEnum.PROCESSED.getLabel());
            tTaskProcessMapper.insert(process1);
        }*/

        //判断该任务的子级任务是否全部签收，全部签收 则视为主任务已完成
        List<TTask> list = tTaskMapper.selectByTaskPid(tTask.getPid());
        boolean tb = true;
        for (TTask t : list) {
            tb = t.getSignStatus() == 1 && tb;
        }
        if (tb) {
            TTask taskParent = tTaskMapper.selectByPrimaryKey(tTask.getPid());
            taskParent.setSignStatus(1);
            taskParent.setResult(IncidentsResultEnum.SIGNATURE.name());
            tTaskMapper.updateByPrimaryKey(taskParent);
        }

        return WrapperResponse.success(condition);
    }

    @Override
    public WrapperResponse<TaskDetailDTO> getTaskDetail(Integer id) {
        TTask tTask = tTaskMapper.selectByPrimaryKey(id);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务不存在！",null);
        }
        TTaskConfig config = tTaskConfigMapper.selectByTaskId(id);
/*        if (Objects.isNull(config)) {
            return WrapperResponse.error(-1,"模型不存在！",null);
        }*/
        TTaskClueRt clueRt = tTaskClueRtMapper.selectByTaskId(id);
        if (Objects.isNull(clueRt)) {
            return WrapperResponse.error(-1,"未找到相关任务关联信息！",null);
        }
        TTaskClueSubject subject = tTaskClueSubjectMapper.selectByPrimaryKey(clueRt.getClueId());
        if (Objects.isNull(subject)) {
            return WrapperResponse.error(-1,"未找到相关线索信息！",null);
        }
        //List<TGangAnalyseDetail> list = tGangAnalyseDetailMapper.selectByTaskCode(tTask.getTaskCode());
        String region = "";
        if (tTask.getPid() != null) {  // 如果是子任务加上子任务的行政区划，否则不用加
            region = tTask.getReceiveBy();
        }
        String uid = tTask.getSendBy();
        // TODO 行政区划修改
        List<TUserMappingDO> userInfos = userMappingService.list();

        //查询出来的列表通过acctId
        List<TUserMappingDO> unique = userInfos.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TUserMappingDO::getUserAcctId))), ArrayList::new)
        );

        Map<String, String> userMap = unique.stream().collect(Collectors.toMap(TUserMappingDO::getUserAcctId, TUserMappingDO::getName));


//        if(StringUtils.isNotEmpty(uid)){
//            WrapperResponse<SysUserDTO> resultBody = uiamService.getUser(uid);
            tTask.setSendBy(userMap.get(uid));
//        }
//        Map<String, List> gangAnaylyselist = gangAnalyseService.getGangAnalyseByTaskCodeAndProvice(tTask.getTaskCode(), region);
        TaskDetailDTO dto = new TaskDetailDTO();
        dto.setTask(tTask);
        dto.setConfig(config);
        dto.setSubject(subject);
        //dto.setDetails(list);
//        dto.setGangAnalyse(gangAnaylyselist);
        return WrapperResponse.success(dto);
    }

    @Override
    public WrapperResponse<PageResult<TTaskProcess>> getFlowPageByCondition(TaskFlowQueryDTO query) {
        if (query.getCondition() == null) {
            return WrapperResponse.success(null);
        }
        Page<TTaskProcess> page =  PageHelper.startPage(query.getPage().getPageNum(), query.getPage().getPageSize());
        List<TTaskProcess> list = tTaskProcessMapper.getFlowPageByCondition(query.getCondition());
        list = list.stream().peek(item -> {
        // TODO 行政区划修改(已改
            List<RegionDO>  regionList = regionService.getRegions(item.getFrom(), item.getTo());

            Map<String, String> regionMap = regionList.stream().map(i -> {
                RegionDTO region = new RegionDTO();
                region.setRegion(i.getRegion()+"");
                region.setRegionName(StringUtils.isEmpty(i.getCity())?i.getProvice():i.getCity());
                return region;
            }).collect(Collectors.toMap(RegionDTO::getRegion, RegionDTO::getRegionName));

            item.setFrom(regionMap.get(item.getFrom()));
            item.setTo(regionMap.get(item.getTo()));

        }).collect(Collectors.toList());

        PageResult<TTaskProcess> result = new PageResult<>();
        result.setData(list);
        result.setPageNum(page.getPageNum());
        result.setPageSize(page.getPageSize());
        result.setPages(page.getPages());
        result.setRecordCounts((int)page.getTotal());
        return WrapperResponse.success(
                result
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WrapperResponse<Boolean> execute(LoginUserDTO loginUser, TaskExecDTO dto) {
        TTaskConfig config = tTaskConfigMapper.selectByTaskId(dto.getTaskId());
        TTask tTask = tTaskMapper.selectByPrimaryKey(dto.getTaskId());
        if (config == null) {
            config = new TTaskConfig();
            BeanUtils.copyProperties(dto, config);
            tTaskConfigMapper.insertSelective(config);
        }
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务分发失败，任务不存在！",null);
        }
        if (tTask.getIsParent() != 1) {
            return WrapperResponse.error(-1,"当前任务为子任务无法执行数据采集！",null);
        }
        if (!IncidentsResultEnum.CREATE.name().equals(tTask.getResult())) {
            return WrapperResponse.error(-1,"任务审核失败，当前任务状态不执行！",null);
        }
        tTask.setExecOptUser(loginUser.getUid());
        tTask.setExecTime(new Date());
        tTask.setResult(IncidentsResultEnum.PROCESSED.name());
        //TODO 设置分析结果数据的taskCode
//        setGangAnalyseTaskCode(tTask.getTaskCode());
        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }

//    private void setGangAnalyseTaskCode(String taskCode) {
//        List<String> taskCodes = gangAnalyseDetailMapper.getNotExsitsGangAnalyseTaskCodes();
//        String source = randomTaskCode(taskCodes);
//        gangAnalyseMapper.updateTaskCode(source, taskCode);
//        gangAnalyseDetailMapper.updateTaskCode(source, taskCode);
//
//    }

    private String randomTaskCode(List<String> taskCodes) {
        Integer index = new Random().nextInt(taskCodes.size());
        return taskCodes.get(index);
    }

    @Override
    public WrapperResponse<Boolean> executeCallback(LoginUserDTO loginUser, Integer taskId) {
        TTask tTask = tTaskMapper.selectByPrimaryKey(taskId);
        if (Objects.isNull(tTask)) {
            return WrapperResponse.error(-1,"任务分发失败，任务不存在！",null);
        }
//        if (tTask.getIsParent()!=1) {
//            return WrapperResponse.error(-1,"当前任务为子任务无法执行数据采集！",null);
//        }
        tTask.setExecOptUser(loginUser.getUid());
        tTask.setExecTime(new Date());
        tTask.setResult(IncidentsResultEnum.PROCESSED.name());

        return WrapperResponse.success(tTaskMapper.updateByPrimaryKeySelective(tTask) > 0);
    }

    @Override
    public WrapperResponse<PageResult<TTask>> getPageSubTaskByCondition(TaskQueryDTO query) {
        if (query.getCondition() == null) {
            return WrapperResponse.success(null);
        }
        Date startTime = null, endTime = null;
        if (Objects.nonNull(query.getCondition())) {
            if (!ArrayUtils.isEmpty(query.getCondition().getTimes())) {
                String start = query.getCondition().getTimes()[0];
                String end = query.getCondition().getTimes()[1];

                if (!StringUtils.isBlank(start)) {
                    startTime = DateUtil.beginOfDay(DateUtil.parseDate(start));
                }
                if (!StringUtils.isBlank(end)) {
                    endTime = DateUtil.beginOfDay(DateUtil.parseDate(end));
                }
            }
        }

        List<TUserMappingDO> userInfos = userMappingService.list();

        //通过acctId去重
        List<TUserMappingDO> unique = userInfos.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TUserMappingDO::getUserAcctId))), ArrayList::new)
        );

        Map<String, String> userMap = unique.stream().collect(Collectors.toMap(TUserMappingDO::getUserAcctId, TUserMappingDO::getName));


        Page<TTask> page = PageHelper.startPage(query.getPage().getPageNum(), query.getPage().getPageSize());
        List<TTask> list = tTaskMapper.getPageSubTaskByCondition(query.getCondition(), startTime, endTime);

        list = list.stream().peek(item -> {
            //TODO 行政区划修改(已改)
//            WrapperResponse<List<SysUserDTO>> res = uiamService.getUserInfos(item.getBackOptUser(), item.getExecOptUser(),
//                    item.getCreateBy(), item.getSendBy(), item.getReceiveUser());
//            if (WrapperResponseUtil.isOk(res)) {
//                List<SysUserDTO> userInfos = WrapperResponseUtil.getData(res);
//
//                Map<String, String> userMap = userInfos.stream().collect(Collectors.toMap(SysUserDTO::getUserId, SysUserDTO::getFullName));
                item.setExecOptUserName(userMap.get(item.getExecOptUser()));
                item.setBackOptUserName(userMap.get(item.getBackOptUser()));
                item.setCreateByName(userMap.get(item.getCreateBy()));
                item.setSendByName(userMap.get(item.getSendBy()));
                item.setReceiveUser(userMap.get(userMap.get(item.getReceiveUser())==null?item.getReceiveUser():userMap.get(item.getReceiveUser())));
//            }

        }).collect(Collectors.toList());

        PageResult<TTask> result = new PageResult<>();
        result.setData(list);
        result.setPageNum(page.getPageNum());
        result.setPageSize(page.getPageSize());
        result.setPages(page.getPages());
        result.setRecordCounts((int)page.getTotal());
        return WrapperResponse.success(
                result
        );

//        return WrapperResponse.success(
//                IPageHelper.toPage(new PageInfo<>(list), TTask.class)
//        );
    }



    @Override
    public WrapperResponse<List<RegionDTO>> getEnableProvinceList(String host,Integer port,String passwd,String userAscm, Integer taskId) {
        //TODO 获取任务关联的线索涉及到的prv列表
        TTask task = tTaskMapper.selectByPrimaryKey(taskId);
        List<TTaskSqlExecute> ls = tTaskSqlExecuteMapper.getClueSqlExecuteBytTaskId(task.getTaskCode());
        String tableName = ls.get(0).getTableName();
        if(StringUtils.isEmpty(tableName)){
            return WrapperResponse.error(-1,"当前任务未配置查询sql语句，请配置！",null);
        }
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(userAscm);
        StringBuffer buffer = new StringBuffer();
        if(enums == UserCategoryEnums.GLOBAL){
            buffer.append("select distinct concat(substring(city_code,1,2),'00') prv from ").append(tableName).append(" where prv is not null");
            //buffer.append("select distinct concat(substring("+ls.get(0).getPrvColumn()+",1,2),'00') prv from ").append(tableName).append(" where prv is not null");
        }else if(enums == UserCategoryEnums.PROVINCE){
            buffer.append("select distinct substring(city_code,1,4) prv from ").append(tableName).append(" where prv is not null and prv like '"+task.getPrv().substring(0,2)+"%'");
            //buffer.append("select distinct substring("+ls.get(0).getPrvColumn()+",1,4) prv from ").append(tableName).append(" where prv is not null and prv like '"+task.getPrv().substring(0,2)+"%'");
        }
        String sql = buffer.toString();
        if(StringUtils.isNotEmpty(sql)){
            List<Map<String, Object>> list = dataFluxService.getTaskSqlExecuteList(host,port, passwd, sql);
            //List<Map<String, Object>> list = getDemo(enums);
            log.info("获取的可用的region数据: " + JSON.toJSONString(list));
            TTask tTask = tTaskMapper.selectByPrimaryKey(taskId);
            if (Objects.nonNull(tTask)) {
                if(CollectionUtil.isNotEmpty(list)){
                    List<RegionDTO> rList = list.stream().filter(e -> StringUtils.isNotEmpty(String.valueOf(e.get("prv")))).map( e ->{
                        RegionDTO regionDTO = new RegionDTO();
                        String prv = String.valueOf(e.get("prv"));
                        regionDTO.setRegion(prv+"00");
                        return regionDTO;
                    }).collect(Collectors.toList());
                    return WrapperResponse.success(rList);
                }
            }
        }
        return WrapperResponse.success(null);
    }

    public static List<Map<String, Object>> getDemo(UserCategoryEnums enums) {
        List<Map<String, Object>> list = Lists.newArrayList();
        String[] gprvs = {"530000","210000","430000","220000","410000"};
        String[] pprvs = {"530300","211000","431000","211200","430300"};
       if(enums == UserCategoryEnums.GLOBAL){
           for(int i=0;i<gprvs.length;i++){
               Map<String, Object> mmp = Maps.newHashMap();
               mmp.put("prv", gprvs[i]);
               list.add(mmp);
           }
       }else{
           for(int i=0;i<pprvs.length;i++){
               Map<String, Object> mmp = Maps.newHashMap();
               mmp.put("prv", pprvs[i]);
               list.add(mmp);
           }
       }
       return list;
    }

    @Override
    public WrapperResponse<PageResult<TTask>> getPageStackTaskByCondition(TaskQueryDTO query) {
        if (query.getCondition() == null) {
            return WrapperResponse.success(null);
        }
        Date startTime = null, endTime = null;
        if (Objects.nonNull(query.getCondition())) {
            if (!ArrayUtils.isEmpty(query.getCondition().getTimes())) {
                String start = query.getCondition().getTimes()[0];
                String end = query.getCondition().getTimes()[1];
                if (StringUtils.isNotBlank(start)) {
                    startTime = DateUtil.beginOfDay(DateUtil.parseDate(start));
                }
                if (StringUtils.isNotBlank(end)) {
                    endTime = DateUtil.beginOfDay(DateUtil.parseDate(end));
                }
            }
        }
        List<TUserMappingDO> userInfos = userMappingService.list();

        //通过acctId去重
        List<TUserMappingDO> unique = userInfos.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TUserMappingDO::getUserAcctId))), ArrayList::new)
        );

        Map<String, String> userMap = unique.stream().collect(Collectors.toMap(TUserMappingDO::getUserAcctId, TUserMappingDO::getName));

        Page<TTask> page = PageHelper.startPage(query.getPage().getPageNum(), query.getPage().getPageSize());
        List<TTask> list = tTaskMapper.getPageStackTaskByCondition(query.getCondition(), startTime, endTime);
        list = list.stream().peek(item -> {
            //TODO 行政区划用户数据(已改)
//            WrapperResponse<List<SysUserDTO>> res = uiamService.getUserInfos(item.getBackOptUser(), item.getExecOptUser(),
//                    item.getCreateBy(), item.getSendBy());
//            if (WrapperResponseUtil.isOk(res)) {
//                List<SysUserDTO> userInfos = WrapperResponseUtil.getData(res);
//
//                Map<String, String> userMap = userInfos.stream().collect(Collectors.toMap(SysUserDTO::getUserId, i -> i.getFullName()));
                item.setExecOptUserName(userMap.get(item.getExecOptUser()));
                item.setBackOptUserName(userMap.get(item.getBackOptUser()));
                item.setCreateByName(userMap.get(item.getCreateBy()));
                item.setSendByName(userMap.get(item.getSendBy()));
//            }
            List<TTask> subTasks = item.getSubTasks();

            subTasks = subTasks.stream().peek(it -> {
                //TODO 行政区划用户数据(已改)
//                WrapperResponse<List<SysUserDTO>> resultBody = uiamService.getUserInfos(it.getBackOptUser(), it.getExecOptUser(),
//                        it.getCreateBy(), it.getSendBy(), it.getReceiveUser());
//                if (WrapperResponseUtil.isOk(resultBody)) {
//                    List<SysUserDTO> userInfos = WrapperResponseUtil.getData(resultBody);
//
//                    Map<String, String> userMap = userInfos.stream().collect(Collectors.toMap(SysUserDTO::getUserId, i -> i.getFullName()));
                    it.setExecOptUserName(userMap.get(it.getExecOptUser()));
                    it.setBackOptUserName(userMap.get(it.getBackOptUser()));
                    it.setCreateByName(userMap.get(it.getCreateBy()));
                    it.setSendByName(userMap.get(it.getSendBy()));
                    it.setReceiveUser(userMap.get(it.getReceiveUser())==null?it.getReceiveUser():userMap.get(it.getReceiveUser()));
//                }
            }).collect(Collectors.toList());
            item.setSubTasks(subTasks);

        }).collect(Collectors.toList());

        PageResult<TTask> result = new PageResult<>();
        result.setData(list);
        result.setPageNum(page.getPageNum());
        result.setPageSize(page.getPageSize());
        result.setPages(page.getPages());
        result.setRecordCounts((int)page.getTotal());
        return WrapperResponse.success(
                result
        );
//        return WrapperResponse.success(
//                IPageHelper.toPage(new PageInfo<>(list), TTask.class)
//        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WrapperResponse<Integer> updateAuthTaskRole(TaskRoleAuthVO vo) {
        List<Integer> taskIds = vo.getTaskIds();
        taskIds.forEach(e ->{
            TTaskRoleAuth auth = new TTaskRoleAuth();
            auth.setTaskId(e);
            auth.setRoleId(vo.getRoleId());
            tTaskRoleAuthMapper.insertSelective(auth);
        });
        return WrapperResponse.success(1);
    }

    @Override
    public WrapperResponse<PageResult<TTask>> getPageByCondition(TaskQueryDTO query) {
        if (query.getCondition() == null) {
            return WrapperResponse.success(null);
        }
        Date startTime = null, endTime = null;
        if (Objects.nonNull(query.getCondition())) {
            if (!ArrayUtils.isEmpty(query.getCondition().getTimes())) {
                String start = query.getCondition().getTimes()[0];
                String end = query.getCondition().getTimes()[1];
                if (StringUtils.isNotBlank(start)) {
                    startTime = DateUtil.beginOfDay(DateUtil.parseDate(start));
                }
                if (StringUtils.isNotBlank(end)) {
                    endTime = DateUtil.beginOfDay(DateUtil.parseDate(end));
                }
            }
        }
        List<TUserMappingDO> userInfos = userMappingService.list();

        //通过acctId去重
        List<TUserMappingDO> unique = userInfos.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TUserMappingDO::getUserAcctId))), ArrayList::new)
        );

        Map<String, String> userMap = unique.stream().collect(Collectors.toMap(TUserMappingDO::getUserAcctId, TUserMappingDO::getName));

        Page<Object> page = PageHelper.startPage(query.getPage().getPageNum(), query.getPage().getPageSize());
        List<TTask> list = tTaskMapper.getPageByCondition(query.getCondition(), startTime, endTime);
        list = list.stream().peek(item -> {
            //TODO 行政区划用户数据(已改)
//            WrapperResponse<List<SysUserDTO>> res = uiamService.getUserInfos(item.getBackOptUser(), item.getExecOptUser(),
//                    item.getCreateBy(), item.getSendBy());
//            if (WrapperResponseUtil.isOk(res)) {
                item.setExecOptUserName(userMap.get(item.getExecOptUser()));
                item.setBackOptUserName(userMap.get(item.getBackOptUser()));
                item.setCreateByName(userMap.get(item.getCreateBy()));
                item.setSendByName(userMap.get(item.getSendBy()));
//            }
            List<TTask> subTasks = item.getSubTasks().stream().filter(e -> e.getBelongTo().equals(query.getCondition().getBelongTo())).collect(Collectors.toList());

            if(CollectionUtil.isNotEmpty(subTasks)){
                subTasks = subTasks.stream().peek(it -> {
//                WrapperResponse<List<SysUserDTO>> resultBody = uiamService.getUserInfos(it.getBackOptUser(), it.getExecOptUser(),
//                        it.getCreateBy(), it.getSendBy(), it.getReceiveUser());
//                if (WrapperResponseUtil.isOk(resultBody)) {
                    item.setExecOptUserName(userMap.get(item.getExecOptUser()));
                    item.setBackOptUserName(userMap.get(item.getBackOptUser()));
                    item.setCreateByName(userMap.get(item.getCreateBy()));
                    item.setSendByName(userMap.get(item.getSendBy()));
//                }
                }).collect(Collectors.toList());
                item.setSubTasks(subTasks);
            }
        }).collect(Collectors.toList());
//        PageInfo<TTask> pageInfo = new PageInfo<>(list);
//        pageInfo.setTotal(page.getTotal());
        PageResult<TTask> result = new PageResult<>();
        result.setData(list);
        result.setPageNum(page.getPageNum());
        result.setPageSize(page.getPageSize());
        result.setPages(page.getPages());
        result.setRecordCounts((int)page.getTotal());
        return WrapperResponse.success(result);
    }

    @Override
    public WrapperResponse<List<TTask>> enableList(UserCategoryEnums enums,String region) {
        List taskList = Lists.newArrayList();
        if(enums == UserCategoryEnums.GLOBAL){
            List<TTask> data = tTaskMapper.selectParentTaskByCategoryAndDescAndPrv(UserCategoryEnums.GLOBAL.toString(),TaskSourceEnums.DIRECT.name(),null);
            //taskList = data.stream().map(e -> new TTask(e.getId(),e.getTaskCode(),e.getTitle())).collect(Collectors.toList());
            taskList = data;
        }else if(enums == UserCategoryEnums.PROVINCE){
            List<TTask> tmpList = Lists.newArrayList();
            List<TTask> signList = tTaskMapper.selectSignedTaskByRegion(region);
            List<TTask> proviceParentList = tTaskMapper.selectParentTaskByCategoryAndDescAndPrv(UserCategoryEnums.PROVINCE.toString(),TaskSourceEnums.DIRECT.name(),region);
            tmpList.addAll(signList);
            tmpList.addAll(proviceParentList);
            //taskList = tmpList.stream().map(e -> new TTask(e.getId(),e.getTaskCode(),e.getTitle())).collect(Collectors.toList());
            taskList = tmpList;
        }else{
            List<TTask> signList = tTaskMapper.selectSignedTaskByRegion(region);
            //taskList = signList.stream().map(e -> new TTask(e.getId(),e.getTaskCode(),e.getTitle())).collect(Collectors.toList());
            taskList = signList;
        }
        return WrapperResponse.success(taskList);
    }

    @Override
    public TTask findById(Integer taskId) {
        return tTaskMapper.selectByPrimaryKey(taskId);
    }

    @Override
    public List<TTask> getRootTaskByBelongTo(String region) {
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(region);
        String belongTo = enums.name();
        List<TTask> result = Lists.newArrayList();
        if(enums == UserCategoryEnums.GLOBAL){
            result = tTaskMapper.selectRootTaskByBelongToAndTaskCode(belongTo,null);
        }else{
            result = tTaskMapper.selectSignedTaskByRegion(region);
        }
        return result;
    }

/*    public static void main(String[] args) throws IOException {
        List<String> dataLs = FileUtils.readLines(new File("d://湘雅附三追加人员数据-wchealthmanager.csv"));
        List<String> result = Lists.newArrayList();
        for (String s:dataLs) {
            String[] str = s.split(",");
            StringBuffer buffer = new StringBuffer("insert into KCH03_NEW(AAB069,AAC002,AAC003,BKH028,SELT_NO) VALUES(");
            for (String val:str) {
                buffer.append("'").append(val).append("',");
            }
            String sql = buffer.toString().substring(0,buffer.length()-1)+");";
            System.out.println();
            result.add(sql);
        }
        FileUtils.writeLines(new File("d://write-sql.sql"),result);
    }*/
}

